<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

// 获取前端传过来的登录信息
$identifier = $_POST['identifier'] ?? '';
$password = $_POST['password'] ?? '';

// 检查账号或邮箱和密码是否为空
if (empty($identifier) || empty($password)) {
    $result = [
        'status' => 'error',
        'message' => '账号/邮箱和密码不能为空'
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

// 创建数据库连接
try {
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 查询用户信息，支持通过账号或邮箱登录
    $loginStmt = $pdo->prepare("SELECT * FROM mi_users WHERE 账号 = :identifier OR 邮箱 = :identifier");
    $loginStmt->bindParam(':identifier', $identifier);
    $loginStmt->execute();
    $user = $loginStmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        // 验证密码
        if ($user['密码'] === $password) {
            // 登录成功，返回用户所有信息
            $result = [
                'status' => 'success',
                'message' => '登录成功',
                'user' => $user
            ];
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
        } else {
            // 密码错误
            $result = [
                'status' => 'error',
                'message' => '密码错误'
            ];
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
        }
    } else {
        // 用户不存在
        $result = [
            'status' => 'error',
            'message' => '用户不存在'
        ];
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
    }

} catch (PDOException $e) {
    // 数据库操作失败
    $result = [
        'status' => 'error',
        'message' => '数据库操作失败：' . $e->getMessage()
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
?>
